<?php

namespace app\api\controller;

use think\Db;

//订单
// 2018-10-26 重大调整  将多产品单地址 和单产品多地址的订单拆分开 单产品单地址的不拆
class Order extends BaseController
{
    //订单列表
    public function getList()
    {
        $user_info = session('user_info');
        $keyword = input('post.keyword', '');
        $status = input('post.status', 0);
        $status = explode(',', $status);
        foreach ($status as $key => $value) {
            $status[$key] = intval($value);
        }
        $limit = input('post.limit', 10);
        $page = input('post.page', 1);
        $order = ['ct' => -1];
        //供应商查看全部自己的产品订单（操作发货退款） 帮主查看帮会所有的订单（只有自有产品才能操作发货退款） 去掉这条 因为没有自有商品 不需要发货 帮主也只能看到自己的订单
        //会员查看自己的订单（代客购买）和粉丝的订单（邀请评价联系帮主）  粉丝查看自己的订单（申请退款、评价）
        $role = intval($user_info['gang_role']);
        if (2 >= $role || 5 == $role) {
            $query['buyer|seller'] = $user_info['id'];
        } elseif (3 == $role) {
            $query['csid'] = $user_info['id'];
        }
        if ($keyword) {
            // 搜索按商品名
            $p_arr = Db::name('product')->where('name', 'like', $keyword)->field('id')->select();
            $ids = [];
            foreach ($p_arr as $key => $value) {
                $ids[] = $value['id'];
            }
            $query['product.product_id'] = ['in', $ids];
        }
        if (5 >= $role && 3 != $role && $user_info['gang_id']) {
            $query['gang_id'] = $user_info['gang_id'];
        }

        $query['status'] = ['in', $status];
        $data = Db::name('order')->where($query)->order($order)->limit($limit)->page($page)->select();
        $result = [];
        $config = config('order_status');
        foreach ($data as $key => $value) {
            $row = [];
            $row['ct'] = date('Y/m/d', $value['ct']);
            $row['id'] = $value['id'];
            foreach ($value['product'] as $k => $v) {
                $prow = [];
                $product_info = Db::name('product')->field('id,name,pic')->find($v['product_id']);
                $prow['name'] = $product_info['name'];
                $prow['pic'] = $product_info['pic'];
                $prow['price'] = round($v['price'], 2);
                $prow['specifications'] = strval($v['specifications']);
                $prow['number'] = strval($v['number']);
                $row['product'][$k] = $prow;
            }
            $row['total_money'] = round($value['total_money'], 2);
            $row['buyer'] = strval($value['buyer']);
            $row['total'] = intval($value['total']);
            $row['price'] = round($value['price'], 2);
            $row['specifications'] = strval($value['specifications']);
            $row['status'] = intval($value['status']);
            if (10 == $row['status']) {
                if ($row['evaluate_time']) {
                    $row['ok_time'] = date('Y/m/d H:i', $value['evaluate_time']);
                } elseif ($row['receive_time']) {
                    $row['ok_time'] = date('Y/m/d H:i', $value['receive_time']);
                }
            }
            $row['status_msg'] = $config[$row['status']];
            foreach ($value['address'] as $k => $v) {
                $address_info = Db::name('address')->find($v['address_id']);
                $row['address'][] = ['consignee' => strval($address_info['consignee']), 'number' => intval($v['number']), 'phone' => strval($address_info['phone']), 'express_code' => strval($v['express_code']), 'express_number' => strval($v['express_number'])];
            }

            $result[] = $row;
        }

        return success(['data' => $result, 'gang_role' => $role]);
    }

    // 计算顺丰邮费
    public function countPostage()
    {
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        $province = input('post.province', '');
        if (!$province) {
            return error('参数错误：错误的province');
        }
        $number = input('post.number', 0);
        if (!$number) {
            return error('参数错误：错误的number');
        }
        $postage_price = calcPostage($product_id, $province, $number);

        return success(['data' => $postage_price]);
    }

    //代客下单(单个产品多个地址)
    public function replaceOrder()
    {
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        $user_info = session('user_info');
        if (!$user_info['openid']) {
            return error('请先微信登录');
        }
        $product_info = Db::name('product')->find($product_id);
        if (!$product_info) {
            return error('未找到该产品');
        }
        $specifications = input('post.specifications', '');
        if (!$specifications) {
            return error('请选择规格');
        }
        $total_number = input('post.total_number', '');
        if (!$total_number) {
            return error('请选择购买数量');
        }
        $address = input('post.address/a', []);
        if (!is_array($address) || count($address) < 1) {
            return error('请选择收货地址');
        }

        $data = input('post.', '');
        $row = $address_row = [];
        $total = 0;

        // 计算顺丰邮费
        if ('顺丰' == $data['express']) {
            $postage_info = Db::name('postage')->where(['admin_id' => $product_info['admin_id'], 'express_code' => 'SF'])->find();
        }
        $postage_price = 0;
        foreach ($address as $key => $value) {
            $number = intval($value['number']);
            $current_postage = 0;
            if ($number <= 0) {
                return error('购买数量必须大于0');
            }
            if (!$value['address_id'] || 24 != strlen($value['address_id'])) {
                return error('收货地址错误');
            }
            // if (!checkPhone($value['phone'])) {
            //     return error('请正确填写收货人的手机号');
            // }
            $address_info = Db::name('address')->where(['id' => $value['address_id'], 'type' => 0])->find();
            if (!$address_info) {
                return error('收货地址错误');
            }
            // 计算顺丰邮费
            if ('顺丰' == $data['express']) {
                $current_postage = calcPostage($product_id, $address_info['province'], $number, $product_info, $postage_info);
                $postage_price += $current_postage;
            }

            $a_row = ['address_id' => $value['address_id'], 'number' => $number];
            if ($current_postage > 0) {
                $a_row['postage'] = $current_postage;
            }
            $address_row[] = $a_row;
        }
        $total = intval($total_number);
        // 计算顺丰邮费
        if ('顺丰' == $data['express']) {
            $row['total_postage'] = $postage_price;
        }
        $stock = 0;
        $stock_index = -1;
        foreach ($product_info['specifications'] as  $key => $value) {
            if ($value['title'] == $specifications) {
                $stock_index = $key;
                $stock = intval($value['stock']);
                break;
            }
        }
        if ($stock < $total) {
            return error('该产品库存不足,最多只能购买'.$stock.'件');
        }
        if ($stock_index != -1) {
            // 减少库存（如果有秒杀 则应该是支付成功后减少库存）
            Db::name('product')->where('id', $product_info['id'])->setDec("specifications.$stock_index.stock", $total);
        }
        //增加销量
        Db::name('product')->where('id', $product_info['id'])->setInc('sales', 1);
        $row['address'] = $address_row;
        // 下版本 多地址这里进行拆单 母单保存子单ids和总金额，支付时用
        if ('顺丰' == $data['express']) {
            $row['express'] = $data['express'];
        }
        if ($data['remark']) {
            $row['remark'] = strval($data['remark']);
        }
        if ($data['sender_name']) {
            $row['sender_name'] = strval($data['sender_name']);
        }
        if ($data['sender_phone']) {
            $row['sender_phone'] = strval($data['sender_phone']);
        }

        $gang_price = Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id'], 'specifications' => $specifications])->find();
        $price = round($gang_price['gang_price'], 2);
        if ($price <= 0) {
            $price = round($product_info['retail_price'], 2);
        }
        $row['total_number'] = $total;
        $row['total_money'] = $price * $total;
        // 计算顺丰邮费
        if ('顺丰' == $data['express']) {
            $row['total_money'] = $row['total_money'] + $postage_price;
        }
        //代客购买 买家和卖家都是自己
        $row['buyer'] = $user_info['id'];
        $row['seller'] = $user_info['id'];
        $row['buyer_ismember'] = 1;
        //买家的入会邀请人 为空则是散客
        if ($user_info['inviter_id']) {
            $row['inviter_id'] = strval($user_info['inviter_id']);
        }
        $row['openid'] = $user_info['openid'];
        $row['gang_id'] = $user_info['gang_id'];
        $gang_info = Db::name('gang')->find($user_info['gang_id']);
        $row['csid'] = $gang_info['csid'];
        $row['product'][] = ['product_id' => $product_id, 'specifications' => $specifications, 'number' => intval($total), 'price' => $price, 'admin_id' => $product_info['admin_id']];
        $row['ct'] = time();
        $row['status'] = 0;
        $row['from'] = 1; //1 代客下单 0 小店下单
        $row['admin_id'] = $product_info['admin_id'];
        $row['type'] = 0; // type 0母单 1子单
        $row['subject'] = $product_info['name'].'_'.$specifications;
        $row['id'] = Db::name('order')->insert($row);
        $row['recharge'] = round($row['total_money'], 2);
        //微信支付
        $wx_service = new \wx\WeixinService();

        return $wx_service->prePay($row);
    }

    //小店下单(多个产品一个地址)
    public function create()
    {
        $product_ids = input('post.product_ids/a', []);
        if (!$product_ids || 0 == count($product_ids)) {
            return error('参数错误：错误的product_ids');
        }
        $address = input('post.address/a', []);
        if (!is_array($address) || count($address) < 1) {
            return error('请选择收货地址');
        }
        $user_info = session('user_info');
        if (!$user_info['openid']) {
            return error('请先微信登录');
        }

        $shop_id = input('post.shop_id', '');
        if (!$shop_id || 24 != strlen($shop_id)) {
            return error('参数错误：错误的shop_id');
        }
        $shop_info = Db::name('shop')->find($shop_id);
        if (!$shop_info) {
            return error('未找到该小店');
        }
        $row = $address_row = [];
        foreach ($address as $value) {
            if (!$value['address_id'] || 24 != strlen($value['address_id'])) {
                return error('收货地址错误');
            }
            $address_info = Db::name('address')->where(['user_id' => $user_info['id'], 'type' => 0])->find();
            if (!$address_info) {
                return error('收货地址错误');
            }
            // 小店下单是单地址 所以直接用最后一个
            $province = $address_info['province'];
            $address_row[] = ['address_id' => $value['address_id'], 'number' => 1];
        }
        $row['address'] = $address_row;
        // 下版本 多商品这里进行拆单 母单保存子单ids和总金额，支付时用（查询时候加type过滤）
        $specifications = input('post.specifications/a', []);
        $numbers = input('post.numbers/a', []);
        $data = input('post.', '');

        $role = 0;
        if ($user_info['gang_id'] == $shop_info['gang_id']) {
            $role = intval($user_info['gang_role']);
        }
        if ('顺丰' == $data['express']) {
            $row['express'] = $data['express'];
        }
        if ($data['remark']) {
            $row['remark'] = strval($data['remark']);
        }
        $total = 0;
        $total_money = 0;
        $total_postage = 0;
        $product_list = [];
        foreach ($product_ids as $key => $product_id) {
            $product_info = Db::name('product')->find($product_id);
            if (!$product_info) {
                return error('未找到'.$product_id.'产品');
            }
            if (!$specifications[$key]) {
                return error('请选择商品['.$product_info['name'].']的规格');
            }
            if (0 == $key) {
                $row['subject'] = $product_info['name'].(1 == count($product_ids) ? '' : '等多件商品');
            }
            $product_list[$product_id] = $product_info;
            $product_number = intval($numbers[$key]);
            if ($product_number <= 0) {
                return error('请选择商品['.$product_info['name'].']的数量');
            }
            $stock = 0;
            $current_spec = [];
            foreach ($product_info['specifications'] as $value) {
                if ($value['title'] == $specifications[$key]) {
                    $stock = intval($value['stock']);
                    $current_spec = $value;
                    break;
                }
            }
            if ($stock < $product_number) {
                return error('商品['.$product_info['name'].']的库存不足,最多只能购买'.$product_info['stock'].'件');
            }
            $price = 0;
            $gang_price = Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $shop_info['gang_id'], 'specifications' => $specifications[$key]])->find();
            if ($role >= 2) {
                $price = round($gang_price['gang_price'], 2);
            }
            if ($price <= 0) {
                $price = round($current_spec['retail_price'], 2);
            }
            $postage_price = 0;
            $row_info = ['product_id' => $product_id, 'specifications' => $specifications[$key], 'number' => $product_number, 'price' => $price, 'admin_id' => $product_info['admin_id']];
            // 现在未拆单直接用最后一个admin_id
            $admin_id = $product_info['admin_id'];
            $row['product'][] = $row_info;
            $total_money += round($product_number * $price + $postage_price, 2);
            $total += $product_number;
        }
        $row['admin_id'] = $admin_id;
        $row['type'] = 0; // type 0母单 1子单
        // 计算顺丰邮费
        if ('顺丰' == $data['express']) {
            $new_product_ids = [];
            $new_numbers = [];
            foreach ($product_ids as $key => $product_id) {
                $f = array_search($product_id, $new_product_ids);
                if (false === $f) {
                    $new_product_ids[] = $product_id;
                }
                $new_numbers[$f] += intval($numbers[$key]);
            }

            foreach ($new_product_ids as $key => $product_id) {
                $f = array_search($product_id, $product_ids);
                $product_number = intval($new_numbers[$key]);
                $product_info = $product_list[$product_id];
                $postage_info = Db::name('postage')->where(['admin_id' => $product_info['admin_id'], 'express_code' => 'SF'])->find();
                $postage_price = calcPostage($product_id, $province, $product_number, $product_info, $postage_info);
                $row['product'][$f]['postage'] = $postage_price;
                $total_postage += $postage_price;
            }
            $row['total_postage'] = $total_postage;
            $total_money += $total_postage;
        }
        foreach ($product_ids as $key => $product_id) {
            $product_info = $product_list[$product_id];
            $stock_index = -1;
            foreach ($product_info['specifications'] as $kk => $value) {
                if ($value['title'] == $specifications[$key]) {
                    $stock_index = $kk;
                    break;
                }
            }
            $product_number = intval($numbers[$key]);
            if ($stock_index != -1) {
                // 减少库存（如果有秒杀 则应该是支付成功后减少库存）
                Db::name('product')->where('id', $product_id)->setDec("specifications.$stock_index.stock", $product_number);
            }
            //增加销量
            Db::name('product')->where('id', $product_id)->setInc('sales', 1);
        }
        $row['total_number'] = $total;
        $row['total_money'] = $total_money;
        $row['buyer'] = $user_info['id'];
        $row['seller'] = $shop_info['user_id'];
        $row['buyer_ismember'] = $role >= 2 ? 1 : 0;
        //买家的入会邀请人 为空则是散客
        if ($user_info['inviter_id']) {
            $row['inviter_id'] = strval($user_info['inviter_id']);
        }
        $row['openid'] = $user_info['openid'];
        $row['gang_id'] = $shop_info['gang_id'];
        $gang_info = Db::name('gang')->find($shop_info['gang_id']);
        $row['csid'] = $gang_info['csid'];
        $row['ct'] = time();
        $row['status'] = 0;
        $row['from'] = 0; //0小店下单
        $row['id'] = Db::name('order')->insert($row);
        $row['recharge'] = round($row['total_money'], 2);

        //微信支付
        $wx_service = new \wx\WeixinService();

        return $wx_service->prePay($row);
    }

    // 立即支付
    public function pay()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $row = Db::name('order')->find($order_id);
        $row['recharge'] = round($row['total_money'], 2);

        //微信支付
        $wx_service = new \wx\WeixinService();

        return $wx_service->prePay($row);
    }

    //申请退款 \ 申请售后
    public function applyRefund()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $form_id = input('post.form_id', '');
        if (!$form_id) {
            return error('参数错误：错误的form_id');
        }
        $reason = input('post.reason', '');
        if (!$reason) {
            return error('请选择退款原因');
        }
        $info = input('post.info', '');
        if (!$info) {
            return error('请填写详情');
        }
        $money = round(input('post.money', 0), 2);
        if (!$money || $money <= 0) {
            return error('请填写退款金额');
        }
        $imgs = input('post.imgs/a', '');
        $user_info = session('user_info');
        //检验是否购买过产品
        $order = Db::name('order')->where('id', $order_id)->find();
        if (!$order) {
            return error('未找到该订单');
        }
        if ($order['buyer'] != $user_info['id']) {
            return error('这不是您的订单');
        }
        if (1 != $order['status'] && 2 != $order['status']) {
            return error('该订单状态不能申请退款');
        }
        if ($order['total_fee'] < $money) {
            return error('最多只能退'.$order['total_fee'].'元!');
        }
        if ($order['send_time'] && $order['send_time'] + 10 * 86400 < time()) {
            return error('订单已超过发货后10天，不能申请退款！');
        }
        $update_row = ['status' => 5, 'reason' => $reason, 'reason_info' => $info, 'apply_refund_money' => $money, 'form_id' => $form_id, 'apply_time' => time()];
        if ($order['send_time']) {
            // 未发货即是 申请退款 已发货是申请售后
            $update_row['apply_imgs'] = $imgs;
            $update_row['status'] = 6;
        }
        Db::name('order')->where(['id' => $order['id']])->update($update_row);
        $wxgzh_service = new \wx\WxgzhService();
        $admin_info = Db::name('admin')->find($order['admin_id']);
        $product = Db::name('product')->field('name')->find($order['product'][0]['product_id']);
        if ($order['send_time'] && $admin_info['gzh_openid']) {
            // 退货 发送公众号模板消息（给供应商）
            $data = [
                'first' => ['value' => '买家申请退货，请及时处理！'],
                'keyword1' => ['value' => strval($order['id'])],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => $order['total_real_supply'].'元'],
                'remark' => ['value' => '原因：'.$reason.'，详情：'.$info],
            ];
            $wxgzh_service->sendTemplateMsg($admin_info['gzh_openid'], 'ZIAeqE5nV9sT4I7X0KLmCO8kMs6_KxQf9LkOu2AN-ng', $data);
        } elseif ($admin_info['gzh_openid']) {
            // 退款 发送公众号模板消息（给供应商）
            $data = [
                'first' => ['value' => '买家申请退款，请及时处理！'],
                'keyword1' => ['value' => $order['total_real_supply'].'元'],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => strval($order['id'])],
                'keyword4' => ['value' => $reason],
                'remark' => ['value' => $info],
            ];
            $wxgzh_service->sendTemplateMsg($admin_info['gzh_openid'], 'RlLrUWzjsVqcRd5DxTDhZ1mti7m97ZFxtKgsNUX_bNI', $data);
        }

        return success();
    }

    //订单详情
    public function getInfo()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $user_info = session('user_info');
        $data = Db::name('order')->find($order_id);
        if (!$data) {
            return error('未找到该订单');
        }
        $order_info = [];
        foreach ($data['product'] as $key => $value) {
            $row = [];
            $product_info = Db::name('product')->field('id,name,pic')->find($value['product_id']);
            $row['product_id'] = strval($value['product_id']);
            $row['admin_id'] = strval($value['admin_id']);
            $row['name'] = $product_info['name'];
            $row['pic'] = $product_info['pic'];
            $row['price'] = round($value['price'], 2);
            $row['specifications'] = strval($value['specifications']);
            $row['number'] = strval($value['number']);
            $order_info['product'][$key] = $row;
        }
        $product_info = Db::name('product')->field('id,name,pic')->find($data['product_id']);
        // 退货地址
        if ((13 == $data['status'] || 4 == $data['status']) && 24 == strlen($data['product'][0]['admin_id'])) {
            $order_info['return_address'] = Db::name('return_address')->where('admin_id', $data['product'][0]['admin_id'])->find();
        }
        $address = [];
        foreach ($data['address'] as $k => $v) {
            $address_info = Db::name('address')->find($v['address_id']);
            $address[] = ['consignee' => strval($address_info['consignee']), 'number' => intval($v['number']), 'phone' => strval($address_info['phone']), 'address' => strval($address_info['address']), 'express_code' => strval($v['express_code']), 'express_number' => strval($v['express_number'])];
        }
        // 新数组装order信息
        $order_info['id'] = $order_id;
        $order_info['address'] = $address;
        $buyer_info = Db::name('user')->field('id,name,avatar,phone')->find($data['buyer']);
        $order_info['total'] = intval($data['total']);
        $order_info['status'] = intval($data['status']);
        $order_info['buyer_info'] = $buyer_info;
        $order_info['total_money'] = round($data['total_money'], 2);
        $order_info['total_postage'] = round($data['total_postage'], 2);
        $order_info['remark'] = strval($data['remark']);
        $order_info['send_time'] = strval($data['send_time']);
        $order_info['sender_name'] = strval($data['sender_name']);
        $order_info['sender_phone'] = strval($data['sender_phone']);
        $order_info['reason'] = strval($data['reason']);
        $order_info['reason_info'] = strval($data['reason_info']);
        $order_info['apply_refund_money'] = round($data['apply_refund_money'], 2);
        $order_info['apply_imgs'] = $data['apply_imgs'] ? $data['apply_imgs'] : [];
        $order_info['ct'] = date('Y年m月d日 H:i:s', $data['ct']);
        $order_info['inviter_id'] = strval($data['inviter_id']);
        $order_info['gang_id'] = strval($data['gang_id']);
        $order_info['buyer'] = strval($data['buyer']);
        $order_info['total_red_packet'] = round($data['total_red_packet'], 2);
        $order_info['buyer_send_number'] = strval($data['buyer_send_number']);
        $order_info['buyer_send_code'] = strval($data['buyer_send_code']);
        $order_info['total_fee'] = round($data['total_fee'], 2);

        //红包预览
        foreach ($data['red_packet'] as $kk => $vv) {
            $order_info['red_packet'][$kk]['money'] = $vv['money'];
            $order_info['red_packet'][$kk]['type'] = $vv['type'];
            $order_info['red_packet'][$kk]['user_info'] = Db::name('user')->field('id,name,avatar')->find($vv['user_id']);
        }

        return success($order_info);
    }

    // 确认收货
    public function confirmReceipt()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $user_info = session('user_info');
        $order_info = Db::name('order')->where(['id' => $order_id, 'buyer' => $user_info['id']])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (2 != $order_info['status']) {
            return error('该订单不是申请退款状态，不能确认退款');
        }

        //确认收货 待评价
        Db::name('order')->where('id', $order_id)->update(['status' => 12, 'receive_time' => time()]);

        // 买家自动收货后将钱打给供应商并写财务明细记录
        financeDetail([$order_info]);

        return success();
    }

    // 确认退款（帮主可以退自有产品、供应商可以退官方的产品）
    public function confirmRefund()
    {
        return error('暂不开放此功能');
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $user_info = session('user_info');
        $order_info = Db::name('order')->where(['id' => $order_id, 'gang_id' => $user_info['gang_id']])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (5 != $order_info['status']) {
            return error('该订单不是申请退款状态，不能确认退款');
        }
        $role = 0;
        if ($user_info['gang_id'] == $order_info['gang_id']) {
            $role = intval($user_info['gang_role']);
        }
        if ($role < 5) {
            return error('您的权限不够');
        }

        Db::name('order')->where('id', $order_id)->update(['status' => 7, 'confirm_refund_time' => time()]);

        //确定后自动退款
        $wx_service = new \wx\WeixinService();
        $result = $wx_service->payOrderRefund($order_info['transaction_id'], $order_info['id'], round($order_info['total_fee'], 2), round($order_info['total_fee'], 2));
        if ('SUCCESS' == $result['return_code'] && 'SUCCESS' == $result['result_code']) {
            Db::name('order')->where('id', $result['out_trade_no'])->update(['status' => 11, 'refund_time' => time()]);

            return success('自动退款成功');
        }

        return success('自动退款失败');
    }

    // 拒绝退款
    public function rejectRefund()
    {
        return error('暂不开放此功能');
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $user_info = session('user_info');
        $order_info = Db::name('order')->where(['id' => $order_id, 'gang_id' => $user_info['gang_id']])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (5 != $order_info['status']) {
            return error('该订单不是申请退款状态，不能拒绝退款');
        }

        $role = 0;
        if ($user_info['gang_id'] == $order_info['gang_id']) {
            $role = intval($user_info['gang_role']);
        }
        if ($role < 5) {
            return error('您的权限不够');
        }

        Db::name('order')->where('id', $order_id)->update(['status' => 8, 'reject_refund_time' => time()]);

        return success();
    }

    // 发货接口
    public function sendGoods()
    {
        return error('暂不开放此功能');
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $user_info = session('user_info');
        $order_info = Db::name('order')->where(['id' => $order_id, 'gang_id' => $user_info['gang_id']])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (1 != $order_info['status']) {
            return error('该订单不是待发货状态');
        }

        $role = 0;
        if ($user_info['gang_id'] == $order_info['gang_id']) {
            $role = intval($user_info['gang_role']);
        }
        if ($role < 5) {
            return error('您的权限不够');
        }
        $codes = input('post.codes/a', []);
        $numbers = input('post.numbers/a', []);
        foreach ($order_info['address'] as $key => $value) {
            if (!$codes[$key]) {
                return error('请选择第'.($key + 1).'个地址的物流公司');
            }
            if (!$numbers[$key]) {
                return error('请选择第'.($key + 1).'个地址的运单号');
            }

            $value['express_code'] = $codes[$key];
            $value['express_number'] = $numbers[$key];
            $order_info['address'][$key] = $value;
        }
        Db::name('order')->where('id', $order_id)->update(['status' => 2, 'send_time' => time(), 'address' => $order_info['address']]);

        return success();
    }

    // 买家退货发单接口
    public function buyerSendGoods()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $code = input('post.code', '');
        if (!$code) {
            return error('参数错误：错误的code');
        }
        $number = input('post.number', '');
        if (!$number) {
            return error('参数错误：错误的number');
        }
        $user_info = session('user_info');
        $order_info = Db::name('order')->where(['id' => $order_id, 'buyer' => $user_info['id']])->find();
        if (!$order_info) {
            return error('未找到该订单');
        }
        if (13 != $order_info['status']) {
            return error('该订单不是待买家发货状态');
        }

        Db::name('order')->where('id', $order_id)->update(['status' => 4, 'buyer_send_time' => time(), 'buyer_send_code' => $code, 'buyer_send_number' => $number]);
        $admin_info = Db::name('admin')->find($order_info['admin_id']);
        $product = Db::name('product')->find($order_info['product'][0]['product_id']);          
        if ($admin_info['gzh_openid']) {
            //  发送公众号模板消息 给供应商
            $wxgzh_service = new \wx\WxgzhService();
            $data = [
                'first' => ['value' => '买家申请退货的订单已经发货！'],
                'keyword1' => ['value' => strval($order_info['id'])],
                'keyword2' => ['value' => strval($product['name'])],
                'keyword3' => ['value' => strval($order_info['product'][0]['number'])],
                'keyword4' => ['value' => strval($order_info['apply_refund_money'].'元')],
                'remark' => ['value' => '买家已发货，请在收货', 'color' => '#173177'],
            ];
            $wxgzh_service->sendTemplateMsg($admin_info['gzh_openid'], 'LTtfunnRUl9VZWqrXQ_LCt2UJhblh8v0-9sJSaSGKrU', $data, 'pages/index/welcome');
        }
        return success();
    }

    //查看物流
    public function getLogistics()
    {
        $express_code = input('post.code', '');
        if (!$express_code) {
            return error('参数错误：错误的快递公司');
        }

        $logisticCode = input('post.num', '');
        if (!$logisticCode) {
            return error('参数错误：错误的运单号');
        }
        // $result = getOrderTracesByJson($express_code, $logisticCode);
        $result = getExpressDetail($express_code, $logisticCode);

        return success($result);
    }
}
